import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpServer {
    private DatagramSocket socket = null;

    public UdpServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //服务器的启动逻辑
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true) {
            //每次循环，就是处理一次请求-响应的过程
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4060],4060);
            socket.receive(requestPacket);
            //把读取的请求转成字符串，方便后续的操作
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.根据请求计算响应
            String response = process(request);
            //3.把响应返回到客户端(对于回显服务器来说，这一步啥也不用做)
            //构造一个DatagramPacket作为响应对象
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),request.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s:%d] req: %s, resp: %s\n",requestPacket.getAddress().toString(),responsePacket.getPort(),request,response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpServer server = new UdpServer(9090);
        server.start();

    }
}
